//
//  home_iPhone_ViewController.m
//  chilemat
//
//  Created by Cristian Gonzalez Figueroa on 21-03-14.
//  Copyright (c) 2014 Chilemat SpA. All rights reserved.
//

#import "home_iPhone_ViewController.h"
#import "classGenericCell.h"
#import "CustomCell.h"
#import "UITabBarController+hidable.h"
#import "dao.h"
#import "Reachability.h"
#import "AppRecord.h"
#import "IconDownloader.h"

@interface home_iPhone_ViewController ()

//@property (nonatomic, strong) NSArray *pageImages;
@property (nonatomic, strong) NSMutableArray *pageImages2;
@property (nonatomic, strong) NSMutableArray *pageViews;

- (void)loadVisiblePages;
- (void)loadPage:(NSInteger)page;
- (void)purgePage:(NSInteger)page;

@property (nonatomic, strong) NSMutableDictionary *imageDownloadsInProgress;

@property (nonatomic, strong) NSMutableDictionary *imageDownloadsInProgressMasVistos;

@property (nonatomic, strong) NSMutableDictionary *imageDownloadsInProgressMarcas;

@end

@implementation home_iPhone_ViewController{
    
    CGFloat startContentOffset;
    CGFloat lastContentOffset;
    BOOL hidden;
}

@synthesize scrollView = _scrollView;
@synthesize scrollViewHomeContent = _scrollViewHomeContent;

@synthesize pageImages2 = _pageImages2;
@synthesize pageViews = _pageViews;
@synthesize tableViewOfertas, tableViewMasVistos, tableViewMarcas;

@synthesize dataArrayOfertas = _dataArrayOfertas;
@synthesize dataArrayMasVistos = _dataArrayMasVistos;
@synthesize dataArrayMarcas = _dataArrayMarcas;
@synthesize dataArraySearch = _dataArraySearch;

@synthesize jsonOfertas;
@synthesize jsonMasVistos;
@synthesize jsonMarcas;
@synthesize jsonBanner;
@synthesize json;

@synthesize imageObjectsOfertas = _imageObjectsOfertas;
@synthesize dataArrayRefreshOfertas = _dataArrayRefreshOfertas;

@synthesize dataArrayRefreshMasVistos = _dataArrayRefreshMasVistos;
@synthesize imageObjectsMasVistos = _imageObjectsMasVistos;
@synthesize imageObjectsMarcas = _imageObjectsMarcas;
@synthesize viewRegister;

bool blnReachabilityHomeiPhone = YES;
int intNroBanner = 0;

UIActivityIndicatorView *aiViewiPhoneBanners;

//Variables para hacer mover los banners principales
//----------------------------------------------------
NSInteger  currentPage   = 1;
NSInteger  numberOfPages = 1;

NSTimer *timerLoadHome;

//----------------------------------------------------

#pragma mark - The Magic!

-(void)expand
{
    if(hidden)
        return;
    
    hidden = YES;
    
  [self.tabBarController setTabBarHidden:YES animated:YES];
    
//[self.navigationController setNavigationBarHidden:YES animated:YES];
}

-(void)contract
{
    if(!hidden)
        return;
    
    hidden = NO;
    
    [self.tabBarController setTabBarHidden:NO
                                  animated:YES];
    
    [self.navigationController setNavigationBarHidden:NO
                                             animated:YES];
}

#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    
    if (scrollView == _scrollViewHomeContent) {
        startContentOffset = lastContentOffset = _scrollViewHomeContent.contentOffset.y;
        //  NSLog(@"scrollViewWillBeginDragging: %f", _scrollViewHomeContent.contentOffset.y);
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{

    if (scrollView == _scrollViewHomeContent) {
        CGFloat currentOffset = _scrollViewHomeContent.contentOffset.y;
        CGFloat differenceFromStart = startContentOffset - currentOffset;
        CGFloat differenceFromLast = lastContentOffset - currentOffset;
        lastContentOffset = currentOffset;
        
        if((differenceFromStart) < 0)
        {
            if(_scrollViewHomeContent.isTracking && (abs(differenceFromLast)>1))
                [self expand];
        }
        else {
            if(_scrollViewHomeContent.isTracking && (abs(differenceFromLast)>1))
                [self contract];
        }
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
}

- (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView
{
    if (scrollView == _scrollViewHomeContent) {
        [self contract];
    }
    
    return YES;
}

//---------------

- (void)loadPage:(NSInteger)page {
    
    if (page < 0 || page >= self.pageImages2.count) {
        // If it's outside the range of what we have to display, then do nothing
        return;
    }

    // Load an individual page, first checking if you've already loaded it
    UIView *pageView = [self.pageViews objectAtIndex:page];
    if ((NSNull*)pageView == [NSNull null]) {
        CGRect frame = self.scrollView.bounds;
        frame.origin.x = frame.size.width * page;
        frame.origin.y = 0.0f;
        
        NSString *strNameImage = @"";
        strNameImage = [self.pageImages2 objectAtIndex:page];
        //-----------------------------------------------------------------------------------
        //Leemos
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
        
        NSString *strNameImageTmp = @"";
        NSString *documentsDirectory = [paths objectAtIndex:0];
        strNameImageTmp = [NSString stringWithFormat:@"%@", strNameImage];
        
        NSString* path = [documentsDirectory stringByAppendingPathComponent:strNameImageTmp ];
        UIImage* imgBanner = [UIImage imageWithContentsOfFile:path];
        //-----------------------------------------------------------------------------------
        
        UIImageView *newPageView = [[UIImageView alloc] initWithImage:imgBanner];
//      newPageView.contentMode = UIViewContentModeScaleAspectFit;
        newPageView.frame = frame;
        [self.scrollView addSubview:newPageView];
        [self.pageViews replaceObjectAtIndex:page withObject:newPageView];
    }
    
}

- (void)purgePage:(NSInteger)page {
    if (page < 0 || page >= self.pageImages2.count) {
        // If it's outside the range of what you have to display, then do nothing
        return;
    }
    
    // Remove a page from the scroll view and reset the container array
    UIView *pageView = [self.pageViews objectAtIndex:page];
    if ((NSNull*)pageView != [NSNull null]) {
        [pageView removeFromSuperview];
        [self.pageViews replaceObjectAtIndex:page withObject:[NSNull null]];
    }
}
/*
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    // Load the pages that are now on screen
    [self loadVisiblePages];
}
*/
- (void)loadVisiblePages {
    // First, determine which page is currently visible
    CGFloat pageWidth = self.scrollView.frame.size.width;
    NSInteger page = (NSInteger)floor((self.scrollView.contentOffset.x * 2.0f + pageWidth) / (pageWidth * 2.0f));
    
    // Work out which pages you want to load
    NSInteger firstPage = page - 1;
    NSInteger lastPage = self.pageImages2.count -1 ; //page + 1;
    
    // Purge anything before the first page
    for (NSInteger i=0; i<firstPage; i++) {
//      [self purgePage:i];
    }
    for (NSInteger i=firstPage; i<=lastPage; i++) {
        [self loadPage:i];
    }
    for (NSInteger i=lastPage+1; i<self.pageImages2.count; i++) {
//      [self purgePage:i];
    }
}

-(NSString*) formatCurrencyValue:(double)value
{
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
    [numberFormatter setCurrencySymbol:@"$"];
    [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
    NSNumber *c = [NSNumber numberWithFloat:value];
    return [numberFormatter stringFromNumber:c];
}

- (NSString *)stringByRemovingControlCharacters: (NSString *)inputString
{
    NSCharacterSet *controlChars = [NSCharacterSet controlCharacterSet];
    NSRange range = [inputString rangeOfCharacterFromSet:controlChars];
    if (range.location != NSNotFound) {
        NSMutableString *mutable = [NSMutableString stringWithString:inputString];
        while (range.location != NSNotFound) {
            [mutable deleteCharactersInRange:range];
            range = [mutable rangeOfCharacterFromSet:controlChars];
        }
        return mutable;
    }
    return inputString;
}

- (void) retrieveDataOfertas{
    
    [_dataArrayOfertas removeAllObjects];
    _dataArrayOfertas = [[NSMutableArray alloc] init];
    
    _imageObjectsOfertas = [[NSMutableArray alloc] init];

    [_dataArrayRefreshOfertas removeAllObjects];
    _dataArrayRefreshOfertas = [[NSMutableArray alloc] init];
    
    dao *objDAO = [[dao alloc] init];
    int intIdUsuario = [objDAO obtainCurrentIdUser];
    
    if (intIdUsuario == -1) {
        intIdUsuario = 1;
    }
    
//------------------------------------------------------------------------------
    NSString *strUrl = [NSString stringWithFormat:@"http://mobileecommerce.elasticbeanstalk.com/MobileJsonHome.aspx?strJsonBase=JsonProductosEventos"];
    
    NSURL *url = [NSURL URLWithString:strUrl];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    
    [NSURLConnection
     sendAsynchronousRequest:urlRequest
     queue:[NSOperationQueue mainQueue]
     completionHandler:^(NSURLResponse *response,
                         NSData *data,
                         NSError *error)
     {
         if ([data length] >0 && error == nil)
         {
             NSLog(@"Load Home ofertas perfecto!!!");
             
             NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
             NSString *strNoData = newStr;
             
             NSLog(@"*******Ofertas = %@", strNoData);
             
             newStr = [self stringByRemovingControlCharacters:newStr];
             
             NSData* dataUTF8 = [newStr dataUsingEncoding:NSUTF8StringEncoding];
             
             jsonOfertas = [NSJSONSerialization JSONObjectWithData:dataUTF8 options:NSJSONReadingMutableLeaves error:nil];

             //ImagenProductos/5/126_4.jpg
             //{"p":"5", "dp":"Alicate corte 6 1/4” 84009. ", "pn":"1900", "po":"300", "do":"70", "sku":"120873 ", "idm":"4", "dmp":"stanley ", "img":"5/126_4.jpg", "vl":"5" }
             
             for (int i = 0; i<jsonOfertas.count; i++)
             {
                 UIActivityIndicatorView *aiViewActivity;
                 aiViewActivity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
                 aiViewActivity.hidesWhenStopped = NO; //I added this just so I could see it
                 aiViewActivity.frame = CGRectMake(0, 0, 48, 48);
                 
                 NSString *strTitleLabel = [[jsonOfertas objectAtIndex:i] objectForKey:@"dp"];
                 NSString *strSubtitleLabel = @"";
                 NSString *strTrademark = [[jsonOfertas objectAtIndex:i] objectForKey:@"dmp"];
                 NSString *strIdmark = [[jsonOfertas objectAtIndex:i] objectForKey:@"idm"];
                 
                 NSString *strSKU = [[jsonOfertas objectAtIndex:i] objectForKey:@"sku"];
                 NSString *strIdProducto = [[jsonOfertas objectAtIndex:i] objectForKey:@"p"];
                 NSString *strReviews = [[jsonOfertas objectAtIndex:i] objectForKey:@"vl"];

                 NSString *strPrice = [self formatCurrencyValue:[[[jsonOfertas objectAtIndex:i] objectForKey:@"po"] doubleValue]];
                 
                 NSString *strOfferPrice = @"";
                 NSString *strPriceDuplicated = strPrice;
                 
                 NSString *strDiscount = @"";
                 
                 NSString *strOfferTime = @"";
                 NSString *strQty = [[jsonOfertas objectAtIndex:i] objectForKey:@"unidad"];
                 
                 AppRecord *appRecord = [[AppRecord alloc] init];
                 
                 classGenericCell *objCell = [[classGenericCell alloc] initClassCell:strTitleLabel andSubtitleLabel:strSubtitleLabel andTrademark:strTrademark andIdMark:strIdmark andSKU:strSKU andStrIdProducto:strIdProducto andReviews:strReviews andstrPrice:strPrice andOfferPrice:strOfferPrice andstrPriceDuplicated:strPriceDuplicated andDiscount:strDiscount andOfferTime:strOfferTime andQty:strQty];
                 
                 [_dataArrayOfertas addObject:objCell];
//-------------------------------------------------------------------------
                 [_dataArrayRefreshOfertas addObject:aiViewActivity];
                 
                 appRecord.imageURLString = [NSString stringWithFormat:@"http://cdn.chilemat.com.s3-sa-east-1.amazonaws.com/ImagenProductos/%@", [[jsonOfertas objectAtIndex:i] objectForKey:@"img"]];
                 
                 [_imageObjectsOfertas addObject:appRecord];
//------------------------------------------------------------------------------------------------------------------
             
                 //------------------------------------------------------------------------------------------------------------------
                 //Quitamos los caracteres especiales para grabar en SqlLite
/*
                  NSString * replace = [strPrice stringByReplacingOccurrencesOfString: @ "$" withString: @ ""];
                  replace = [replace stringByReplacingOccurrencesOfString: @ "." withString: @ ""];
                  int intPrecio = [ [replace stringByReplacingOccurrencesOfString: @ " C/U" withString: @ ""] intValue];
                  
                  replace = [strOfferPrice stringByReplacingOccurrencesOfString: @ "$" withString: @ ""];
                  replace = [replace stringByReplacingOccurrencesOfString: @ "." withString: @ ""];
                  int intPrecioOferta = [ [replace stringByReplacingOccurrencesOfString: @ " C/U" withString: @ ""] intValue];
                  
                  NSLog(@"intPrecioOferta =%i", intPrecioOferta);
                  
                  NSLog(@"strIdProducto =%i", [strIdProducto intValue]);
                  
                  [objDAO insertProduct:intIdUsuario intIdProducto:[strIdProducto intValue] strDescProd:strTitleLabel strDescComplementaria:strSubtitleLabel strOverview:@"" strSKU:strSKU intNroReviews:[strReviews intValue] intNroValoraciones:0 intPrecio:intPrecio intPrecioOferta:intPrecioOferta intDescuento:[strDiscount intValue] strTiempoOferta:strOfferTime intIdMarca:[strIdmark intValue] strDescripcionMarca:strTrademark];
*/
                 //------------------------------------------------------------------------------------------------------------------
             
             }

             if (_dataArrayOfertas.count >= 1) {
                 
                 [self.tableViewOfertas reloadData];
                 
                 NSIndexPath *topIndexPath = [NSIndexPath indexPathForRow:_dataArrayOfertas.count-1
                                                                inSection:0];
                 
                 [self.tableViewOfertas scrollToRowAtIndexPath:topIndexPath
                                              atScrollPosition:UITableViewScrollPositionNone
                                                      animated:YES];
             }else{
             
                 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                 message:strNoData
                                                                delegate:nil
                                                       cancelButtonTitle:@"OK"
                                                       otherButtonTitles:nil];
                 [alert show];
             }

         }
         else if ([data length] == 0 && error == nil)
         {
             NSLog(@"Nothing was downloaded.");
             
             UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                             message:@"Nothing Ofertas."
                                                            delegate:nil
                                                   cancelButtonTitle:@"OK"
                                                   otherButtonTitles:nil];
             [alert show];
             
         }
         else if (error != nil){
             NSLog(@"Error = %@", error);
             
             UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                             message:[NSString stringWithFormat:@"Ofertas.- %@", error]
                                                            delegate:nil
                                                   cancelButtonTitle:@"OK"
                                                   otherButtonTitles:nil];
             [alert show];
             
         }
     }];
//------------------------------------------------------------------------------

}

- (void) retrieveDataMasVistos{

    [_dataArrayMasVistos removeAllObjects];
    _dataArrayMasVistos = [[NSMutableArray alloc] init];
    
    _imageObjectsMasVistos = [[NSMutableArray alloc] init];
    
    [_dataArrayRefreshMasVistos removeAllObjects];
    _dataArrayRefreshMasVistos = [[NSMutableArray alloc] init];
    
    dao *objDAO = [[dao alloc] init];
    int intIdUsuario = [objDAO obtainCurrentIdUser];
    
    if (intIdUsuario == -1) {
        intIdUsuario = 1;
    }
    
    //------------------------------------------------------------------------------
    NSString *strUrl = [NSString stringWithFormat:@"http://mobileecommerce.elasticbeanstalk.com/MobileJsonHome.aspx?strJsonBase=JsonProductosMasVistos"];
    
    NSURL *url = [NSURL URLWithString:strUrl];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    
    [NSURLConnection
     sendAsynchronousRequest:urlRequest
     queue:[NSOperationQueue mainQueue]
     completionHandler:^(NSURLResponse *response,
                         NSData *data,
                         NSError *error)
     {
         if ([data length] >0 && error == nil)
         {
             NSLog(@"Load Home mas vistos perfecto!!!");
             
             NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
             NSString *strNoData = newStr;

             NSLog(@"********Mas Vistos = %@", strNoData);

             
             newStr = [self stringByRemovingControlCharacters:newStr];
             
             NSData* dataUTF8 = [newStr dataUsingEncoding:NSUTF8StringEncoding];
             
             jsonMasVistos = [NSJSONSerialization JSONObjectWithData:dataUTF8 options:NSJSONReadingMutableLeaves error:nil];
             
             //ImagenProductos/5/126_4.jpg
             //{"p":"5", "dp":"Alicate corte 6 1/4” 84009. ", "pn":"1900", "po":"300", "do":"70", "sku":"120873 ", "idm":"4", "dmp":"stanley ", "img":"5/126_4.jpg", "vl":"5" }]
             
             for (int i = 0; i<jsonMasVistos.count; i++)
             {
                 UIActivityIndicatorView *aiViewActivity;
                 aiViewActivity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
                 aiViewActivity.hidesWhenStopped = NO; //I added this just so I could see it
                 aiViewActivity.frame = CGRectMake(0, 0, 48, 48);
                 
                 NSString *strTitleLabel = [[jsonMasVistos objectAtIndex:i] objectForKey:@"dp"];
                 NSString *strSubtitleLabel = @"";
                 NSString *strTrademark = [[jsonMasVistos objectAtIndex:i] objectForKey:@"dmp"];
                 NSString *strIdmark = [[jsonMasVistos objectAtIndex:i] objectForKey:@"idm"];
                 
                 NSString *strSKU = [[jsonMasVistos objectAtIndex:i] objectForKey:@"sku"];
                 NSString *strIdProducto = [[jsonMasVistos objectAtIndex:i] objectForKey:@"p"];
                 NSString *strReviews = [[jsonMasVistos objectAtIndex:i] objectForKey:@"vl"];
                 
                 NSString *strPrice = [self formatCurrencyValue:[[[jsonMasVistos objectAtIndex:i] objectForKey:@"pn"] doubleValue]];
                 
                 NSString *strOfferPrice = @"";
                 NSString *strPriceDuplicated = strPrice;
                 
                 NSString *strDiscount = @"";
                 
                 NSString *strOfferTime = @"";
                 NSString *strQty = [[jsonMasVistos objectAtIndex:i] objectForKey:@"unidad"];
                 
                 AppRecord *appRecord = [[AppRecord alloc] init];
                 
                 classGenericCell *objCell = [[classGenericCell alloc] initClassCell:strTitleLabel andSubtitleLabel:strSubtitleLabel andTrademark:strTrademark andIdMark:strIdmark andSKU:strSKU andStrIdProducto:strIdProducto andReviews:strReviews andstrPrice:strPrice andOfferPrice:strOfferPrice andstrPriceDuplicated:strPriceDuplicated andDiscount:strDiscount andOfferTime:strOfferTime andQty:strQty];
                 
                 [_dataArrayMasVistos addObject:objCell];
                 //-------------------------------------------------------------------------
                 [_dataArrayRefreshMasVistos addObject:aiViewActivity];
                 
                 appRecord.imageURLString = [NSString stringWithFormat:@"http://cdn.chilemat.com.s3-sa-east-1.amazonaws.com/ImagenProductos/%@", [[jsonMasVistos objectAtIndex:i] objectForKey:@"img"]];
                 
                 [_imageObjectsMasVistos addObject:appRecord];
                 //------------------------------------------------------------------------------------------------------------------
                 //Quitamos los caracteres especiales para grabar en SqlLite
                 /*
                  NSString * replace = [strPrice stringByReplacingOccurrencesOfString: @ "$" withString: @ ""];
                  replace = [replace stringByReplacingOccurrencesOfString: @ "." withString: @ ""];
                  int intPrecio = [ [replace stringByReplacingOccurrencesOfString: @ " C/U" withString: @ ""] intValue];
                  
                  replace = [strOfferPrice stringByReplacingOccurrencesOfString: @ "$" withString: @ ""];
                  replace = [replace stringByReplacingOccurrencesOfString: @ "." withString: @ ""];
                  int intPrecioOferta = [ [replace stringByReplacingOccurrencesOfString: @ " C/U" withString: @ ""] intValue];
                  
                  NSLog(@"intPrecioOferta =%i", intPrecioOferta);
                  
                  NSLog(@"strIdProducto =%i", [strIdProducto intValue]);
                  
                  [objDAO insertProduct:intIdUsuario intIdProducto:[strIdProducto intValue] strDescProd:strTitleLabel strDescComplementaria:strSubtitleLabel strOverview:@"" strSKU:strSKU intNroReviews:[strReviews intValue] intNroValoraciones:0 intPrecio:intPrecio intPrecioOferta:intPrecioOferta intDescuento:[strDiscount intValue] strTiempoOferta:strOfferTime intIdMarca:[strIdmark intValue] strDescripcionMarca:strTrademark];
                  */
                 //------------------------------------------------------------------------------------------------------------------
             }
             
             if (_dataArrayMasVistos.count >= 1) {

                 [self.tableViewMasVistos reloadData];
                 
                 NSIndexPath *topIndexPath = [NSIndexPath indexPathForRow:_dataArrayMasVistos.count-1
                                                                inSection:0];
                 
                 [self.tableViewMasVistos scrollToRowAtIndexPath:topIndexPath
                                              atScrollPosition:UITableViewScrollPositionNone
                                                      animated:YES];
             }else{
             
                 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                 message:strNoData
                                                                delegate:nil
                                                       cancelButtonTitle:@"OK"
                                                       otherButtonTitles:nil];
                 [alert show];
             }
             
         }
         else if ([data length] == 0 && error == nil)
         {
             NSLog(@"Nothing was downloaded.");
             
             UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                             message:@"Nothing Mas Vistos."
                                                            delegate:nil
                                                   cancelButtonTitle:@"OK"
                                                   otherButtonTitles:nil];
             [alert show];
             
         }
         else if (error != nil){
             NSLog(@"Error = %@", error);
             
             UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                             message:[NSString stringWithFormat:@"Mas Vistos.- %@", error]
                                                            delegate:nil
                                                   cancelButtonTitle:@"OK"
                                                   otherButtonTitles:nil];
             [alert show];
             
         }
     }];
    //------------------------------------------------------------------------------

}

- (void) retrieveDataMarcas{
    
    [_dataArrayMarcas removeAllObjects];
    _dataArrayMarcas = [[NSMutableArray alloc] init];
    
    _imageObjectsMarcas = [[NSMutableArray alloc] init];

    NSString *strUrl = [NSString stringWithFormat:@"http://mobileecommerce.elasticbeanstalk.com/MobileJsonHome.aspx?strJsonBase=JsonMarcasProductos"];
    
    NSURL *url = [NSURL URLWithString:strUrl];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    
    [NSURLConnection
     sendAsynchronousRequest:urlRequest
     queue:[NSOperationQueue mainQueue]
     completionHandler:^(NSURLResponse *response,
                         NSData *data,
                         NSError *error)
     {
         if ([data length] >0 && error == nil)
         {
             NSLog(@"Load Home marcas perfecto!!!");

             NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
             NSString *strNoData = newStr;
             
             NSLog(@"*********Marcas = %@", strNoData);

             newStr = [self stringByRemovingControlCharacters:newStr];
             
             NSData* dataUTF8 = [newStr dataUsingEncoding:NSUTF8StringEncoding];

             //[{"idm":"2", "dmp":"otto", "img":"2.jpg" }, {"idm":"3", "dmp":"otta", "img":"3.jpg" }, {"idm":"4", "dmp":"stanley ", "img":"4.jpg" }, {"idm":"5", "dmp":"teka ", "img":"5.jpg" }, {"idm":"6", "dmp":"polpaico", "img":"6.jpg" }, {"idm":"7", "dmp":"mademsa", "img":"7.jpg" }, {"idm":"8", "dmp":"fensa", "img":"8.jpg" }]
             
             jsonMarcas = [NSJSONSerialization JSONObjectWithData:dataUTF8 options:NSJSONReadingMutableLeaves error:nil];
             
             for (int i = 0; i<jsonMarcas.count; i++)
             {
                 NSString *strTitleLabel = @"";
                 NSString *strSubtitleLabel = @"";
                 NSString *strTrademark = [[jsonMarcas objectAtIndex:i] objectForKey:@"dmp"];
                 NSString *strIdmark = [[jsonMarcas objectAtIndex:i] objectForKey:@"idm"];
                 
                 NSString *strSKU = @"";
                 NSString *strIdProducto = [[jsonMarcas objectAtIndex:i] objectForKey:@"dmp"];
                 NSString *strReviews = @"";
                 NSString *strPrice = @"";
                 NSString *strOfferPrice = @"";
                 NSString *strPriceDuplicated = @"";
                 NSString *strDiscount = @"";
                 NSString *strOfferTime = @"";
                 NSString *strQty = @"";
                 
                 AppRecord *appRecord = [[AppRecord alloc] init];
                 
                 classGenericCell *objCell = [[classGenericCell alloc] initClassCell:strTitleLabel andSubtitleLabel:strSubtitleLabel andTrademark:strTrademark andIdMark:strIdmark andSKU:strSKU andStrIdProducto:strIdProducto andReviews:strReviews andstrPrice:strPrice andOfferPrice:strOfferPrice andstrPriceDuplicated:strPriceDuplicated andDiscount:strDiscount andOfferTime:strOfferTime andQty:strQty];
                 
                 [_dataArrayMarcas addObject:objCell];
                 
                 appRecord.imageURLString = [NSString stringWithFormat:@"http://cdn.chilemat.com.s3-sa-east-1.amazonaws.com/Marcas/%@", [[jsonMarcas objectAtIndex:i] objectForKey:@"img"]];
                 
                 [_imageObjectsMarcas addObject:appRecord];
             }
             
             if (_dataArrayMarcas.count >= 1) {
                 
                 [self.tableViewMarcas reloadData];
                 
                 NSIndexPath *topIndexPath = [NSIndexPath indexPathForRow:_dataArrayMarcas.count-1
                                                                inSection:0];
                 
                 [self.tableViewMarcas scrollToRowAtIndexPath:topIndexPath
                                                atScrollPosition:UITableViewScrollPositionNone
                                                        animated:YES];
             }else{
                 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                 message:strNoData
                                                                delegate:nil
                                                       cancelButtonTitle:@"OK"
                                                       otherButtonTitles:nil];
                 [alert show];

             }

         }
         else if ([data length] == 0 && error == nil)
         {
             NSLog(@"Nothing was downloaded.");
             
             UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                             message:@"Nothing Marcas."
                                                            delegate:nil
                                                   cancelButtonTitle:@"OK"
                                                   otherButtonTitles:nil];
             [alert show];
             
         }
         else if (error != nil){
             NSLog(@"Error = %@", error);

             UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                             message:[NSString stringWithFormat:@"Marcas.- %@", error]
                                                            delegate:nil
                                                   cancelButtonTitle:@"OK"
                                                   otherButtonTitles:nil];
            [alert show];
             
         }
     }];
    
}

- (IBAction)searchProducts:(id)sender {
/*
    UIViewController *rvController = [self.storyboard instantiateViewControllerWithIdentifier:@"searchProducts"];
    [self presentViewController:rvController animated:YES completion:nil];

    UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main_iPhone" bundle:nil];
    UITabBarController *tab = [mainStoryBoard instantiateViewControllerWithIdentifier:@"TabBarView"];
    [tab setSelectedIndex:1];
    
    [self presentViewController:tab animated:YES completion:nil];
*/
    dao *objDAO = [[dao alloc] init];
    
    [objDAO insertSearchBack:1]; //1.- Viene desde el buscar del home
    
    [self.tabBarController setSelectedIndex:1];
}

- (IBAction)callNumber:(id)sender {
    
    NSString *strContactPhone;

    dao *objDAO = [[dao alloc] init];
    
    strContactPhone = [NSString stringWithFormat:@"tel://%@", [objDAO obtainCallCenterNumber]];
    
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:strContactPhone]];
}

- (IBAction)detailProduct:(id)sender {
    
    UIButton *btnClick = sender;
//----------------------------------------------------------------------------------
    NSLog(@"objCell.strIdProducto = %@", btnClick.titleLabel.text);
    
    //Indicamos el producto actual seleccionado para luego obtener su información
    dao *objDAO = [[dao alloc] init];
    
    [objDAO deleteCurrentProduct];
    
    [objDAO insertCurrentProduct:[btnClick.titleLabel.text intValue]];
    
//----------------------------------------------------------------------------------
    [self setBackProductoDetail];

    [self expand];

    [self performSegueWithIdentifier:@"segueProductDetail" sender:nil];
}

- (IBAction)detailProductMoreView:(id)sender {
    
    UIButton *btnClick = sender;
    
    //----------------------------------------------------------------------------------
    NSLog(@"objCell.strIdProducto = %@", btnClick.titleLabel.text);
    
    //Indicamos el producto actual seleccionado para luego obtener su información
    dao *objDAO = [[dao alloc] init];
    
    [objDAO deleteCurrentProduct];
    
    [objDAO insertCurrentProduct:[btnClick.titleLabel.text intValue]];
    
    //----------------------------------------------------------------------------------

    [self setBackProductoDetail];

    [self expand];
    
    [self performSegueWithIdentifier:@"segueProductDetail" sender:nil];
}

-(void)setBackProductoDetail{

    dao *objDAO = [[dao alloc] init];
    
    if ([objDAO obtainProductBack] == -1) { //No hay nada
        [objDAO insertProductBack:0];   //Indica que busca desde el Home
    }else{
        [objDAO updateProductBack:0];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == tableViewOfertas) {
        
        return [_dataArrayOfertas count];
        
    }else if (tableView == tableViewMasVistos) {
        
        return [_dataArrayMasVistos count];
        
    }else{ //Marcas
        return [_dataArrayMarcas count];
    }
}
/*
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    if (tableView == tableViewOfertas) {

        classGenericCell *objCell = [_dataArrayOfertas objectAtIndex:indexPath.row];

        NSLog(@"objCell.strIdProducto=%@", objCell.strIdProducto);
        //viewControllerOfertas
    }
}
*/

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        
        cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault
                                 reuseIdentifier:CellIdentifier];
    }

    if (tableView == tableViewOfertas){
        
        classGenericCell *objCell = [_dataArrayOfertas objectAtIndex:indexPath.row];
        cell.lblTrademark.text = objCell.strTrademark;
        cell.lblTitleLabel.text = objCell.strTitleLabel;
        cell.lblPrice.text = objCell.strPrice;
        
        AppRecord *appRecord = [self.imageObjectsOfertas objectAtIndex:indexPath.row];

        //-----------------------------------------------------------------------------------
        //Leemos
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
        
        //1.- Imagen normal
        NSString *strNameImageTmp = @"";
        NSString *documentsDirectory = [paths objectAtIndex:0];
        strNameImageTmp = [NSString stringWithFormat:@"strIdProducto_%@.jpg", objCell.strIdProducto];
        
        NSString* path = [documentsDirectory stringByAppendingPathComponent:strNameImageTmp ];
        UIImage* image = [UIImage imageWithContentsOfFile:path];
        //-----------------------------------------------------------------------------------
        
        if (image == nil) {

            [self startIconDownloadOfertas:appRecord forIndexPath:indexPath celda:cell action:@"LoadImageFirstTime"];
        }else{

            CGSize itemSize = CGSizeMake(115, 85);
            UIGraphicsBeginImageContextWithOptions(itemSize, NO, 0.0f);
            CGRect imageRect = CGRectMake(0, 0, itemSize.width, itemSize.height);
            [image drawInRect:imageRect];
            cell.imgImageView.image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            cell.imgImageView.frame = CGRectMake(0, 0, 115, 85);
            
//          [self startIconDownloadOfertas:appRecord forIndexPath:indexPath celda:cell action:@"updateImage"];
        }
        
        cell.btnProduct.titleLabel.text = objCell.strIdProducto;
        cell.lblQty.text = objCell.strQty;
        
        CGAffineTransform objTransFormRotate = CGAffineTransformMakeRotation(-M_PI_2);
        cell.transform = objTransFormRotate;
        
        return cell;

    }else if (tableView == tableViewMasVistos) {
        
        classGenericCell *objCell = [_dataArrayMasVistos objectAtIndex:indexPath.row];
        cell.lblTrademark.text = objCell.strTrademark;
        cell.lblTitleLabel.text = objCell.strTitleLabel;
        cell.lblPrice.text = objCell.strPrice;
        cell.imgImageView.image = nil;
        cell.lblQty.text = objCell.strQty;
        
        AppRecord *appRecord = [self.imageObjectsMasVistos objectAtIndex:indexPath.row];
        
        //-----------------------------------------------------------------------------------
        //Leemos
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
        
        //1.- Imagen normal
        NSString *strNameImageTmp = @"";
        NSString *documentsDirectory = [paths objectAtIndex:0];
        strNameImageTmp = [NSString stringWithFormat:@"strIdProducto_%@.jpg", objCell.strIdProducto];
        
        NSString* path = [documentsDirectory stringByAppendingPathComponent:strNameImageTmp ];
        UIImage* image = [UIImage imageWithContentsOfFile:path];
        //-----------------------------------------------------------------------------------
        
        if (image == nil) {

            //[self startIconDownload:appRecord forIndexPath:indexPath celda:cell action:@"LoadImageFirstTime"];
            [self startIconDownloadMasVistos:appRecord forIndexPath:indexPath celda:cell action:@"LoadImageFirstTime"];

            NSLog(@"LoadImageFirstTime MasVistos");
            
        }else{
            CGSize itemSize = CGSizeMake(115, 85);
            UIGraphicsBeginImageContextWithOptions(itemSize, NO, 0.0f);
            CGRect imageRect = CGRectMake(0, 0, itemSize.width, itemSize.height);
            [image drawInRect:imageRect];
            cell.imgImageView.image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            cell.imgImageView.frame = CGRectMake(0, 0, 115, 85);
            
//          [self startIconDownloadMasVistos:appRecord forIndexPath:indexPath celda:cell action:@"updateImage"];

            NSLog(@"updateImage MasVistos");
        }
        
        cell.btnProduct.titleLabel.text = objCell.strIdProducto;
        
        CGAffineTransform objTransFormRotate = CGAffineTransformMakeRotation(-M_PI_2);
        cell.transform = objTransFormRotate;
        
        return cell;
        
    }else{ //Marcas

        classGenericCell *objCell = [_dataArrayMarcas objectAtIndex:indexPath.row];
        cell.lblTrademark.text = objCell.strIdMark;
        
        AppRecord *appRecord = [self.imageObjectsMarcas objectAtIndex:indexPath.row];
        
        //-----------------------------------------------------------------------------------
        //Leemos
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
        
        //1.- Imagen normal
        NSString *strNameImageTmp = @"";
        NSString *documentsDirectory = [paths objectAtIndex:0];
        strNameImageTmp = [NSString stringWithFormat:@"idMarca_%@.jpg", objCell.strIdMark];
        
        NSString* path = [documentsDirectory stringByAppendingPathComponent:strNameImageTmp ];
        UIImage* image = [UIImage imageWithContentsOfFile:path];
        //-----------------------------------------------------------------------------------
        
        if (image == nil) {
            
            //[self startIconDownload:appRecord forIndexPath:indexPath celda:cell action:@"LoadImageFirstTime"];
            [self startIconDownloadMarcas:appRecord forIndexPath:indexPath celda:cell action:@"LoadImageFirstTime"];
            
        }else{
            
            CGSize itemSize = CGSizeMake(120, 89);
            UIGraphicsBeginImageContextWithOptions(itemSize, NO, 0.0f);
            CGRect imageRect = CGRectMake(5, 0, itemSize.width, itemSize.height);
            [image drawInRect:imageRect];
            cell.imgImageView.image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            cell.imgImageView.frame = CGRectMake(5, 0, 120, 89);
            
//            [self startIconDownloadMarcas:appRecord forIndexPath:indexPath celda:cell action:@"updateImage"];
        }
        
//      cell.imgImageView.image = [UIImage imageNamed:@"img_marca.png"];
        
        CGAffineTransform objTransFormRotate = CGAffineTransformMakeRotation(-M_PI_2);
        cell.transform = objTransFormRotate;
        
        return cell;
    }
}

- (void)startIconDownloadMarcas:(AppRecord *)appRecord forIndexPath:(NSIndexPath *)indexPath celda:(CustomCell *) celda action:(NSString *) action
{
    IconDownloader *iconDownloader = [self.imageDownloadsInProgressMarcas objectForKey:indexPath];
    
    if (iconDownloader == nil)
    {
        iconDownloader = [[IconDownloader alloc] init];
        iconDownloader.appRecord = appRecord;
        [iconDownloader setCompletionHandler:^{
            
            celda.imgImageView.image = appRecord.appIcon;
            celda.imgImageView.frame = CGRectMake(5, 0, 120, 89);
            

            [self.imageDownloadsInProgressMarcas removeObjectForKey:indexPath];
            
            //---------------------------------------------------------------------------------------------------
            classGenericCell *objCell = [_dataArrayMarcas objectAtIndex:indexPath.row];
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                                 NSUserDomainMask, YES);
            NSString *documentsDirectory = [paths objectAtIndex:0];
            
            NSString *strNameImageTmp = [NSString stringWithFormat:@"idMarca_%@.jpg", objCell.strIdMark];
            
            NSString* path = [documentsDirectory stringByAppendingPathComponent:strNameImageTmp];
            NSData* data = UIImageJPEGRepresentation(appRecord.appIcon, 1);
            [data writeToFile:path atomically:YES];
            //---------------------------------------------------------------------------------------------------
            
        }];
        [self.imageDownloadsInProgressMarcas setObject:iconDownloader forKey:indexPath];
        [iconDownloader startDownload];
    }
}

- (void)startIconDownloadMasVistos:(AppRecord *)appRecord forIndexPath:(NSIndexPath *)indexPath celda:(CustomCell *) celda action:(NSString *) action
{
    IconDownloader *iconDownloader = [self.imageDownloadsInProgressMasVistos objectForKey:indexPath];
    
    if (iconDownloader == nil)
    {
        iconDownloader = [[IconDownloader alloc] init];
        iconDownloader.appRecord = appRecord;
        [iconDownloader setCompletionHandler:^{

            if ([action  isEqual: @"LoadImageFirstTime"]) {
                
                if (appRecord.appIcon == nil){
                    
                    celda.imgImageView.image = [UIImage imageNamed:@"nofoto.jpg"];
                    appRecord.appIcon = [UIImage imageNamed:@"nofoto.jpg"];
                }else{
                    
                    celda.imgImageView.image = appRecord.appIcon;
                }

                celda.imgImageView.frame = CGRectMake(5, 0, 120, 89);
            }

            [self.imageDownloadsInProgressMasVistos removeObjectForKey:indexPath];
            
            //---------------------------------------------------------------------------------------------------
            classGenericCell *objCell = [_dataArrayMasVistos objectAtIndex:indexPath.row];
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                                 NSUserDomainMask, YES);
            NSString *documentsDirectory = [paths objectAtIndex:0];
            
            NSString *strNameImageTmp = [NSString stringWithFormat:@"strIdProducto_%@.jpg", objCell.strIdProducto];
            
            NSString* path = [documentsDirectory stringByAppendingPathComponent:strNameImageTmp];
            NSData* data = UIImageJPEGRepresentation(appRecord.appIcon, 1);
            [data writeToFile:path atomically:YES];
            //---------------------------------------------------------------------------------------------------
            
        }];
        [self.imageDownloadsInProgressMasVistos setObject:iconDownloader forKey:indexPath];
        [iconDownloader startDownload];
    }
}

- (void)startIconDownloadOfertas:(AppRecord *)appRecord forIndexPath:(NSIndexPath *)indexPath celda:(CustomCell *) celda action:(NSString *) action
{
    IconDownloader *iconDownloader = [self.imageDownloadsInProgress objectForKey:indexPath];
    
    if (iconDownloader == nil)
    {
        iconDownloader = [[IconDownloader alloc] init];
        iconDownloader.appRecord = appRecord;
        [iconDownloader setCompletionHandler:^{

            if ([action  isEqual: @"LoadImageFirstTime"]) {
                
                if (appRecord.appIcon == nil){
                    
                    celda.imgImageView.image = [UIImage imageNamed:@"nofoto.jpg"];
                    appRecord.appIcon = [UIImage imageNamed:@"nofoto.jpg"];
                }else{
                    
                    celda.imgImageView.image = appRecord.appIcon;
                }
                
                celda.imgImageView.frame = CGRectMake(5, 0, 120, 89);
            }
            
            [self.imageDownloadsInProgress removeObjectForKey:indexPath];
            
            //---------------------------------------------------------------------------------------------------
            classGenericCell *objCell = [_dataArrayOfertas objectAtIndex:indexPath.row];
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                                 NSUserDomainMask, YES);
            NSString *documentsDirectory = [paths objectAtIndex:0];
            
            NSString *strNameImageTmp = [NSString stringWithFormat:@"strIdProducto_%@.jpg", objCell.strIdProducto];
            
            NSString* path = [documentsDirectory stringByAppendingPathComponent:strNameImageTmp];
            NSData* data = UIImageJPEGRepresentation(appRecord.appIcon, 1);
            [data writeToFile:path atomically:YES];
            //---------------------------------------------------------------------------------------------------
            
        }];
        [self.imageDownloadsInProgress setObject:iconDownloader forKey:indexPath];
        [iconDownloader startDownload];
    }
}

-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

   dao *objDAO = [[dao alloc] init];
   
    [objDAO deleteProductBack];
    [objDAO insertProductBack:0]; //Volver desde el home
    
    if (tableView == tableViewOfertas){

        classGenericCell *objCell = [_dataArrayOfertas objectAtIndex:indexPath.row];

         NSLog(@"objCell.strIdProducto = %@", objCell.strIdProducto);

        //Indicamos el producto actual seleccionado para luego obtener su información
        
        [objDAO deleteCurrentProduct];
        
        [objDAO insertCurrentProduct:[objCell.strIdProducto intValue]];
        
    }else if (tableView == tableViewMasVistos) {

        classGenericCell *objCell = [_dataArrayMasVistos objectAtIndex:indexPath.row];
        
        NSLog(@"objCell.strIdProducto = %@", objCell.strIdProducto);
        
        //Indicamos el producto actual seleccionado para luego obtener su información
        
        [objDAO deleteCurrentProduct];
        [objDAO insertCurrentProduct:[objCell.strIdProducto intValue]];
        
    }else{
        NSLog(@"Test");
    }

}

- (void)reachabilityDidChange:(NSNotification *)notification {
    Reachability *reachability = (Reachability *)[notification object];
    
    if ([reachability isReachable]) {
        NSLog(@"Reachable");
    } else {
        NSLog(@"Unreachable");
        
        if (blnReachabilityHomeiPhone) {

            blnReachabilityHomeiPhone = NO;
/*
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                            message:@"No existe conexión a internet, intente nuevamente."
                                                           delegate:nil
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
            [alert show];
*/
        }

    }
}

- (void)showTabBar {
    
    UITabBar *tabBar = self.tabBarController.tabBar;
    UIView *parent = tabBar.superview; // UILayoutContainerView
    UIView *content = [parent.subviews objectAtIndex:0];  // UITransitionView
    UIView *window = parent.superview;
    
    [UIView animateWithDuration:0.5
                     animations:^{
                         CGRect tabFrame = tabBar.frame;
                         tabFrame.origin.y = CGRectGetMaxY(window.bounds) - CGRectGetHeight(tabBar.frame);
                         tabBar.frame = tabFrame;
                         
                         CGRect contentFrame = content.frame;
                         contentFrame.size.height -= tabFrame.size.height;
                     }];
    
}

- (void)downloadImageWithURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, UIImage *image))completionBlock
{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                               if ( !error )
                               {
                                   UIImage *image = [[UIImage alloc] initWithData:data];
                                   completionBlock(YES,image);
                               } else{
                                   completionBlock(NO,nil);
                               }
                           }];
}

-(void) bannerInformation{

  [_dataArraySearch removeAllObjects];
   _dataArraySearch = [[NSMutableArray alloc] init];
    
  aiViewiPhoneBanners = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
  aiViewiPhoneBanners.hidesWhenStopped = YES; //I added this just so I could see it
  
  aiViewiPhoneBanners.frame = CGRectMake(140, 55, 50, 50);
    
  [aiViewiPhoneBanners startAnimating];
    
  [self.scrollView addSubview:aiViewiPhoneBanners];
    
//--------
    self.pageImages2 = [[NSMutableArray alloc] init];
    
    NSString *strUrl = [NSString stringWithFormat:@"http://mobileecommerce.elasticbeanstalk.com/MobileJsonHome.aspx?strJsonBase=JsonBanner&strTipoBanner=2"];
    
    NSURL *url = [NSURL URLWithString:strUrl];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    
    [NSURLConnection
     sendAsynchronousRequest:urlRequest
     queue:[NSOperationQueue mainQueue]
     completionHandler:^(NSURLResponse *response,
                         NSData *data,
                         NSError *error)
     {
         if ([data length] >0 && error == nil)
         {
             NSLog(@"Load banners perfecto!!!");
             
             NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
             NSString *strNoData = newStr;
             
             NSLog(@"******Banners = %@", strNoData);
             
             newStr = [self stringByRemovingControlCharacters:newStr];
             
             NSData* dataUTF8 = [newStr dataUsingEncoding:NSUTF8StringEncoding];
             
             //[{"idb":"1", "db":"PRINCIPAL", "img":"banner1_iPhone01.jpg", "param":"intIdAccion=1&intIdProducto=393&intIdCategoria=-1&strStringBusqueda=-1"}]
             
             jsonBanner = [NSJSONSerialization JSONObjectWithData:dataUTF8 options:NSJSONReadingMutableLeaves error:nil];
             
             for (int i = 0; i<jsonBanner.count; i++)
             {
                 NSString *strImage = [[jsonBanner objectAtIndex:i] objectForKey:@"img"];
                 NSString *strUrlImgMarca = [NSString stringWithFormat:@"http://cdn.chilemat.com.s3-sa-east-1.amazonaws.com/Banner/Mobile/iPhone/%@", [[jsonBanner objectAtIndex:i] objectForKey:@"img"]];
                 NSURL *urlMarca = [NSURL URLWithString:strUrlImgMarca];
                 NSString *strParam = [[jsonBanner objectAtIndex:i] objectForKey:@"param"];
                 
                 [_dataArraySearch addObject:strParam];
                 
                 [self downloadImageWithURL:urlMarca completionBlock:^(BOOL succeeded, UIImage *image) {
                     if (succeeded) {
                         
                         //---------------------------------------------------------------------------------------------------
                         NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                                              NSUserDomainMask, YES);
                         NSString *documentsDirectory = [paths objectAtIndex:0];
                         
                         NSString *strNameImageTmp = [NSString stringWithFormat:@"%@", strImage];
                         
                         NSLog(@"strImage=%@", strImage);
                         
                         NSString* path = [documentsDirectory stringByAppendingPathComponent:strNameImageTmp];
                         NSData* data = UIImageJPEGRepresentation(image, 1);
                         [data writeToFile:path atomically:YES];
                         
                         intNroBanner = intNroBanner + 1;
                         
                         [self.pageImages2 addObject:strImage];
                         
                         if (intNroBanner == jsonBanner.count) { //Asíncronamente se cargaron los banner al inicio
                             [self cargarBanner];
                             [aiViewiPhoneBanners startAnimating];
                         }
                         //---------------------------------------------------------------------------------------------------
                     }
                 }];
             }
             
         }
         else if ([data length] == 0 && error == nil)
         {
             NSLog(@"Nothing was downloaded.");

             UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                             message:@"Nothing Banner."
                                                            delegate:nil
                                                   cancelButtonTitle:@"OK"
                                                   otherButtonTitles:nil];
             [alert show];
         
         }
         else if (error != nil){
             NSLog(@"Error = %@", error);
             
             UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                             message:[NSString stringWithFormat:@"Banner.- %@", error]
                                                            delegate:nil
                                                   cancelButtonTitle:@"OK"
                                                   otherButtonTitles:nil];
             [alert show];
             
         }
     }];
}

-(void)scrollToPage:(NSInteger)aPage{

    float myPageWidth = [self.scrollView frame].size.width;
    
    NSInteger temp = aPage*myPageWidth;
    
    NSLog(@"temp = %li", (long)temp);

    NSLog(@"aPage*myPageWidth = %f", aPage*myPageWidth);
    
    [self.scrollView setContentOffset:CGPointMake(aPage*myPageWidth,0) animated:YES];

}

-(void)scrollPages{
    [self scrollToPage:currentPage%numberOfPages];
    NSLog(@"currentPage = %li", currentPage);

    NSLog(@"self.pageImages2.count =%lu", self.pageImages2.count);

    dao *objDAO = [[dao alloc] init];
    
    int intCurrentPage = (int) currentPage;
    
    [objDAO deleteSelectedBanner];
    [objDAO insertSelectedBanner:intCurrentPage];
    
    currentPage++;
    
    if (currentPage == self.pageImages2.count) {
        currentPage = 0;
    }
}

-(void) cargarBanner{

//---------------------------------------------------------------------
//  self.pageImages2 = [[NSMutableArray alloc] init];

//---------------------------------------------------------------------
/*
    [self.pageImages2 addObject:@"banner-principal-iphone-2.png"];
    [self.pageImages2 addObject:@"banner-principal-iphone.jpg"];
    [self.pageImages2 addObject:@"banner-principal-iphone-3.png"];
*/
    NSInteger pageCount = self.pageImages2.count;

//---------------------------------------------------------------------
//Llamamos la carga para mover automáticamente los banners

    numberOfPages = self.pageImages2.count;
    currentPage = 0;

    timerLoadHome = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(scrollPages) userInfo:nil repeats:YES];

//---------------------------------------------------------------------
    
    self.pageViews = [[NSMutableArray alloc] init];
    for (NSInteger i = 0; i < pageCount; ++i) {
        [self.pageViews addObject:[NSNull null]];
    }
    
    // Set up the content size of the scroll view
    CGSize pagesScrollViewSize = self.scrollView.frame.size;
    self.scrollView.contentSize = CGSizeMake(pagesScrollViewSize.width * self.pageImages2.count, pagesScrollViewSize.height);
    
    // Load the initial set of pages that are on screen
    [self loadVisiblePages];
    //----------------------------------------------------------------
}

-(void) crearUsrCloud{

    NSString *strUrl = [NSString stringWithFormat:@"http://mobileecommerce.elasticbeanstalk.com/MobileJsonRegistraUsuario.aspx?strJsonBase=JsonUsuarioIns"];
    
    NSURL *url = [NSURL URLWithString:strUrl];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    
    [NSURLConnection
     sendAsynchronousRequest:urlRequest
     queue:[NSOperationQueue mainQueue]
     completionHandler:^(NSURLResponse *response,
                         NSData *data,
                         NSError *error)
     {
         if ([data length] >0 && error == nil)
         {
             NSLog(@"Crear Usuario perfecto");
             
             NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
             newStr = [self stringByRemovingControlCharacters:newStr];
             
             NSData* dataUTF8 = [newStr dataUsingEncoding:NSUTF8StringEncoding];
             
             //[{"usr":"21"}]
             
             json = [NSJSONSerialization JSONObjectWithData:dataUTF8 options:NSJSONReadingMutableLeaves error:nil];
             
             int intIdUsuario = [  [[json objectAtIndex:0] objectForKey:@"usr"] intValue];

             NSLog(@"intIdUsuario =%i", intIdUsuario);
             
             dao *objDAO = [[dao alloc] init];
             
             [objDAO deleteCurrentIdUser];
             [objDAO insertCurrentIdUser:intIdUsuario];
             
             //strSocialLoginId = 3 //Correo
             [objDAO deleteUserSistem:intIdUsuario];
             
             int intRetorno = [objDAO insertUserSistem:intIdUsuario strUser:@"" strPassword:@"" strSocialLoginId:@"3" strEmail:@""];
             
             NSLog(@"intRetorno =%i", intRetorno);
             
         }
         else if ([data length] == 0 && error == nil)
         {
             NSLog(@"Nothing was downloaded.");
         }
         else if (error != nil){
             NSLog(@"Error = %@", error);
         }
     }];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self showTabBar];

    [self loadTabbar];

    intNroBanner = 0;
    
    blnReachabilityHomeiPhone = YES;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityDidChange:) name:kReachabilityChangedNotification object:nil];
    
    dao *objDAO = [[dao alloc] init];

//******
//Inicializamos el banner
    [objDAO deleteSelectedBanner];
    [objDAO insertSelectedBanner:0];
    
    [self scrollToPage:0];

//******
    int intCurrentIdUser = [objDAO obtainCurrentIdUser];

    if (intCurrentIdUser < 0) {//Si no existe lo pedimos crear
        [self crearUsrCloud];
    }
//-----------------------------------------------------------------------
//Observación: Si está registrado debe desaparecer el botón registrarse.
    
    int intIdUsrRegistered = 0;
    
    intIdUsrRegistered = [objDAO obtainUsrRegistered:intCurrentIdUser];
    
    if (intIdUsrRegistered != -1) { //Registrado
        //Si
        viewRegister.hidden = YES;
        
    }else{ //No registrado
        //No
        viewRegister.hidden = NO;
    }
//-----------------------------------------------------------------------
    
//Obtener el dato desde JSON remotamente y almacenarlo.
    [objDAO deleteCallCenterNumber]; //Remmplazar despues por un update
    [objDAO insertCallCenterNumber:@"0224998624"];
    [objDAO deleteProductsAll];
    
    _scrollViewHomeContent.delegate = self;
    
    hidden = NO;
  
    self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"iphone_header.png"] forBarMetrics:UIBarMetricsDefault];

    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSString *myString = [prefs stringForKey:@"keyToLookupString"];
    
    if ([myString  isEqual: @"LoadHomeFirst"]) {

        //--------------------------------------------------------------------------
        //Observación: Probamos la carga de los banner desde AWS
        [self bannerInformation];
        //--------------------------------------------------------------------------
        
        [self retrieveDataOfertas];
        
        [self retrieveDataMasVistos];
        
        [self retrieveDataMarcas];

        [prefs setObject:@"LoadHomeComplete" forKey:@"keyToLookupString"];
    }else{
    
        [self cargarBanner];
    }

//--------------------------------------------------------------------------
    CGAffineTransform rotateTable = CGAffineTransformMakeRotation(+M_PI_2);

    tableViewOfertas.transform = rotateTable;
//  tableViewOfertas.frame = CGRectMake(0, 500,tableViewOfertas.frame.size.width, tableViewOfertas.frame.size.height);
//  tableViewOfertas.frame = CGRectMake(0, 500,320, 130);
//  [tableViewOfertas setFrame:CGRectMake(0, 0,130, 320)];

    
    tableViewMasVistos.transform = rotateTable;
//    tableViewMasVistos.frame = CGRectMake(0, 500,tableViewMasVistos.frame.size.width, tableViewMasVistos.frame.size.height);
    
    tableViewMarcas.transform = rotateTable;
//    tableViewMarcas.frame = CGRectMake(0, 500,tableViewMarcas.frame.size.width, tableViewMarcas.frame.size.height);

    //Marcamos el Banner 0 por defecto
    [objDAO deleteSelectedBanner];
    [objDAO insertSelectedBanner:0];
    
    //Indicamos por defecto que no se trata de una búsqueda por banner
    [objDAO deleteSearchBanner];
    [objDAO insertSelectedBanner:0];

//--------------------------------------------------------------------------
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapGestureCaptured:)];
    [self.scrollView addGestureRecognizer:singleTap];
}

- (void) loadTabbar{
    //-------------------------------------------------------------------------------------
    dao *objDAO = [[dao alloc] init];
    int intIdUsuario = [objDAO obtainCurrentIdUser];
/*
    if (intIdUsuario == -1) {
        intIdUsuario = 1;
    }
*/
    NSArray *ArrayResumeShoppingCart;
    NSString *strTotalCarro = @"0";
    
    
    ArrayResumeShoppingCart = [objDAO obtainResumeShoppingCart:intIdUsuario];
    
    if (ArrayResumeShoppingCart.count > 0) {
        
        NSLog(@"strTotal =%i", [ArrayResumeShoppingCart[0] intValue] );
        NSLog(@"strCantidadTotal =%i", [ArrayResumeShoppingCart[1] intValue] );
        
        strTotalCarro = ArrayResumeShoppingCart[1];
    }
    
    //----------------------------------
    UITabBar *tabBar = self.tabBarController.tabBar; //tabBarController.tabBar;
    UITabBarItem *tabBarItem1 = [tabBar.items objectAtIndex:0];
    UITabBarItem *tabBarItem2 = [tabBar.items objectAtIndex:1];
    UITabBarItem *tabBarItem3 = [tabBar.items objectAtIndex:2];
    UITabBarItem *tabBarItem4 = [tabBar.items objectAtIndex:3];
    UITabBarItem *tabBarItem5 = [tabBar.items objectAtIndex:4];
    
    tabBarItem1.selectedImage = [[UIImage imageNamed:@"icon_inicio_activo.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem1.image = [[UIImage imageNamed:@"icon_inicio.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem1.title = @"Inicio";
    
    tabBarItem2.selectedImage = [[UIImage imageNamed:@"icon_buscar_activo.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem2.image = [[UIImage imageNamed:@"icon_buscar.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem2.title = @"Buscar";
    
    tabBarItem3.selectedImage = [[UIImage imageNamed:@"icon_carro_activo.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem3.image = [[UIImage imageNamed:@"icon_carro.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem3.title = @"Carro";
    tabBarItem3.badgeValue = strTotalCarro;
    
    tabBarItem4.selectedImage = [[UIImage imageNamed:@"icon_cuenta_activo.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem4.image = [[UIImage imageNamed:@"icon_cuenta.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem4.title = @"Cuenta";
    
    tabBarItem5.selectedImage = [[UIImage imageNamed:@"icon_chat_activo.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem5.image = [[UIImage imageNamed:@"icon_chat.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem5.title = @"Chat";
    
    //------------------------------------------------------------------------------------------------
    //Debemos grabar en SQLite que el banner inicial es indice "0"
    
    //Debemos grabar en SQLite que la accion por defecto es "no" hay busqueda desde el banner central
    //------------------------------------------------------------------------------------------------
}

- (void)singleTapGestureCaptured:(UITapGestureRecognizer *)gesture
{
//  CGPoint touchPoint=[gesture locationInView:self.scrollView];
    
//1.- Detectamos un evento en el banner
    NSLog(@"Tap banner");
    
//2.- Indicamos en SQLite en una tabla que se ejecuta la acción de buscar desde el banner
    
//3.- Enviamos a un segue hacia la búsqueda
    
//4.- Indicamos por defecto que no se trata de una búsqueda por banner
    dao *objDAO = [[dao alloc] init];

    int intBannerSeleccted = [objDAO obtainSelectedBanner];
    int intIdUsuario = [objDAO obtainCurrentIdUser];
    
    NSLog(@"intBannerSeleccted =%i", intBannerSeleccted);

    //Por si acaso borramos los filtros de precios
    [objDAO deleteUserFilterPrice:intIdUsuario];
    
/*
     Tabla: IMAGENES_BANNER
     Nuevo campo: IB_URL_PARAMETROS_MOBILE
     
     Acciones:
     1.- Directo a un producto
     2.- Búsqueda normal
     3.- Búsqueda por departamento tipo Google
     
     Formato:
     intIdAccion=1
     intIdProducto=393
     intIdCategoria=
     strStringBusqueda=
     
     Formato Mobile:
     intIdAccion=1&intIdProducto=393&intIdCategoria=-1&strStringBusqueda=-1
     intIdAccion=2&intIdProducto=-1&intIdCategoria=-1&strStringBusqueda=Alicate
     intIdAccion=3&intIdProducto=-1&intIdCategoria=31&strStringBusqueda=-1
*/
    id IdOptionSearch = [_dataArraySearch objectAtIndex:intBannerSeleccted];

    NSArray *ArrayOptionsCludBanner = [IdOptionSearch componentsSeparatedByString: @"&"];
    
    NSArray *ArrayIdAccion = [[ArrayOptionsCludBanner objectAtIndex: 0] componentsSeparatedByString: @"="];
    
    int intIdOptionSearch = [ [ArrayIdAccion objectAtIndex: 1] intValue];
    
    if (intIdOptionSearch == 1) {

        NSArray *ArrayIdProducto = [[ArrayOptionsCludBanner objectAtIndex: 1] componentsSeparatedByString: @"="];

        int intIdProducto = [ [ArrayIdProducto objectAtIndex: 1] intValue];
        //----------------------------------------------------------------------------------
        [objDAO deleteCurrentProduct];
        [objDAO insertCurrentProduct:intIdProducto];
        
        //----------------------------------------------------------------------------------
        [self setBackProductoDetail];
        [self expand];
        [self performSegueWithIdentifier:@"segueProductDetail" sender:nil];

    }else if (intIdOptionSearch == 2){

        [objDAO deleteCurrentProduct];
        NSArray *ArrayStringSearch = [[ArrayOptionsCludBanner objectAtIndex: 3] componentsSeparatedByString: @"="];
        
        NSString *strStringSearch = [ArrayStringSearch objectAtIndex: 1];
        
        NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
        
        [prefs setObject:strStringSearch forKey:@"StringSearch"];
        [prefs setObject:@"0" forKey:@"strIdDepartment"]; //Identifica el Id de departamento si la búsqueda es por este concepto

        [self performSegueWithIdentifier:@"segueSearchByDepth" sender:nil];
        
    
    }else if (intIdOptionSearch == 3){

        [objDAO deleteCurrentProduct];
        NSArray *ArrayIdDepartmemt = [[ArrayOptionsCludBanner objectAtIndex: 2] componentsSeparatedByString: @"="];
        
        NSString *strIdDepartment = [ArrayIdDepartmemt objectAtIndex: 1];
        
        NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

        [prefs setObject:@"" forKey:@"StringSearch"];
        [prefs setObject:strIdDepartment forKey:@"strIdDepartment"]; //Identifica el Id de departamento si la búsqueda es por este concepto

        [self performSegueWithIdentifier:@"segueSearchByDepth" sender:nil];
    }
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if(timerLoadHome)
    {
        [timerLoadHome invalidate];
        timerLoadHome = nil;
    }
    
    int indexOfPage = scrollView.contentOffset.x / scrollView.frame.size.width;
    
    NSLog(@"indexOfPage =%i", indexOfPage);

    dao *objDAO = [[dao alloc] init];
    
    [objDAO deleteSelectedBanner];
    [objDAO insertSelectedBanner:indexOfPage];
}

- (void)viewWillDisappear:(BOOL)animated{

    if(timerLoadHome)
    {
        [timerLoadHome invalidate];
        timerLoadHome = nil;
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.scrollView.delegate = self;
    
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"segueRegistro"])
    {
        NSLog(@"Segue !!!!!!!");

        dao *objDAO = [[dao alloc] init];
        
        //0 = Home App
        //1 = Register
        //2 = Edición del despacho
        
        [objDAO deleteRegisterBack];
        [objDAO insertRegisterBack:0];

        //Al terminar el proceso de registro debe volver al area personal del usuario.
        NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
        
        [prefs setObject:@"2" forKey:@"strCurrentTypeOfLogin"]; //1: Login normal, 2: Login desde el área personal
        
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
